package com.itboye.ihomebank.activity.qianyue.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.QianYueAdapter;
import com.itboye.ihomebank.base.BaseFragment;
import com.itboye.ihomebank.bean.QianYueManageBean;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.custom.MyListView;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

import static com.itboye.ihomebank.activity.qianyue.ActivityMySign.ONRESTART;

/**
 * 签约（待签约）
 */
@SuppressLint("ValidFragment")
public class OrderFragment extends BaseFragment implements Observer{
	TextView txt_title;
	private int pageNo = 1;
	int status;
	SmartRefreshLayout refresh;
	private ListView xlistView;
	private QianYueAdapter adapter;
	public static String REFRESH = "refresh";
	HousePresenter housePresenter;
	LinearLayout noData;
	String uid = "";
	private MaterialHeader mMaterialHeader;
	private ArrayList<QianYueManageBean> orderQueryModel = new ArrayList<>();

	public OrderFragment(int status) {
		this.status = status;
	}

	public static OrderFragment context;

	public static OrderFragment getInstance() {
		return context;
	}

	@Override
	public int initView() {
		return R.layout.activity_allorder;
	}

	@Override
	public void onMyActivityCreated() {
		// TODO Auto-generated method stub
		Log.d("fragment==","onMyActivityCreated");
		context = this;
		showProgressDialog("数据加载中请稍后", true);
		refresh();
		caozuo();

		adapter = new QianYueAdapter(getActivity(), orderQueryModel,
				R.layout.item_allorder);
		xlistView.setAdapter(adapter);

		IntentFilter filter = new IntentFilter(REFRESH);
		getActivity().registerReceiver(receiver, filter);
	}
	private void caozuo(){
		mMaterialHeader = (MaterialHeader)refresh.getRefreshHeader();
		refresh.setPrimaryColorsId(android.R.color.holo_green_light, android.R.color.white);
		refresh.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）

		//        //触发自动刷新
		refresh.autoRefresh();
		refresh.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh(RefreshLayout refreshlayout) {
				refreshlayout.getLayout().postDelayed(new Runnable() {
					@Override
					public void run() {
						pageNo = 1;
						refresh();
					}
				}, 0);
			}
		});

		//进行加载更多的逻辑处理
		refresh.setOnLoadmoreListener(new OnLoadmoreListener() {
			@Override
			public void onLoadmore(RefreshLayout refreshlayout) {
				refreshlayout.getLayout().postDelayed(new Runnable() {
					@Override
					public void run() {
						pageNo = 1;
						refresh();
					}
				}, 0);
			}
		});

		//refresh.setRefreshHeader(new MaterialHeader(getActivity()).setShowBezierWave(true));
		refresh.setRefreshFooter(new BallPulseFooter(getActivity()).setSpinnerStyle(SpinnerStyle.Scale));
		refresh.finishLoadmore();
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d("fragment==","onResume");
		if (ONRESTART==1){
           refresh.autoRefresh();
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d("fragment==","onStart");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("fragment==","onDestroy");
		getActivity().unregisterReceiver(receiver);
	}

	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		Log.d("fragment==","onAttach");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Log.d("fragment==","onAttach");
		return super.onCreateView(inflater, container, savedInstanceState);

	}


	public void refresh(){
		uid = SPUtils.get(getActivity(), null, SPContants.USER_ID, "") + "";
		housePresenter = new HousePresenter(this);
		housePresenter.qianYueGuanLi(uid, status + "");
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String contraNo = intent.getStringExtra("contractNo");
			String shenfen = intent.getStringExtra("shenfen");
			Iterator<QianYueManageBean> iterator = arrayList.iterator();
			while (iterator.hasNext()) {
				QianYueManageBean bean = iterator.next();
				if (contraNo != null) {
					if (contraNo.equals(bean.getContractNo())
							&& shenfen.equals(bean.getUserType())) {
						bean.setLesserWritten("1");
						adapter.notifyDataSetChanged();
						break;
					}
				}
			}
		}
	};
	private List<QianYueManageBean> arrayList;

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == housePresenter.qianYueGuanLi_success) {
				arrayList = (List<QianYueManageBean>) entity.getData();
				if (pageNo == 1) {//下拉刷新
					orderQueryModel.clear();
					adapter.notifyDataSetChanged();
					//结束加载
					refresh.finishRefresh();
					refresh.finishLoadmore();
				}
				if (arrayList != null) {
					if (arrayList.size() > 0) {
						orderQueryModel.addAll(arrayList);
						noData.setVisibility(View.GONE);
						xlistView.setVisibility(View.VISIBLE);
					} else {
						noData.setVisibility(View.VISIBLE);
						xlistView.setVisibility(View.GONE);
					}
				} else {
					noData.setVisibility(View.VISIBLE);
					xlistView.setVisibility(View.GONE);
				}
			}else if (entity.getEventType() == housePresenter.qianYueGuanLi_fail){
				ByAlert.alert(entity.getMsg());
				refresh.finishLoadmore();
				refresh.finishRefresh();
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}


}
